package yn.micro.web.filter;

import org.springframework.stereotype.Component;
import yn.micro.common.context.ReqNoContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import static yn.micro.common.constants.CommonConstant.REQUEST_NO_HEADER_NAME;

/**
 * 对请求生成唯一序列编码
 *
 * @author yjs
 * @date 2020-12-11 18:09
 */
@Component
public class RequestNoFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            // 生成唯一请求号uuid
            String requestNo = UUID.randomUUID().toString();

            // 增加响应头的请求号
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.addHeader(REQUEST_NO_HEADER_NAME, requestNo);

            // 临时存储
            ReqNoContext.set(requestNo);

            // 放开请求
            chain.doFilter(request, response);

        } finally {
            // 清除临时存储的唯一编号
            ReqNoContext.remove();
        }
    }
}